var common = require('../../../util/common');

module.exports = function(app) {
    return new Handler(app);
};

var Handler = function(app) {
    this.app = app;
    this.sceneId = this.app.getCurServer().scene;
    this.channelService = this.app.get('channelService');
    this.backendSessionService = this.app.get("backendSessionService");
    this.channel = this.channelService.getChannel('scene_' + this.sceneId, true);
    this.cachedb = this.app.get('cachedb');
    this.sceneCacheKey = 'scene_' + this.sceneId;
};

// 进入场景
Handler.prototype.join = function(player, cb) {
    var channel = this.channel;
    var channelService = this.channelService;
    var sceneId = this.sceneId;
    var cachedb = this.cachedb;
    var sceneCacheKey = this.sceneCacheKey;

    this.backendSessionService.getByUid(player.sid, player.uid, function(err, sessions) {
        if (err || sessions === 'undefined' || sessions.length === 0) throw new Error('get backend session failed!');
        common.launchFiber(function() {
            var param = {
                route: 'onJoin',
                name: player.name,
                sid: sessions[0].frontendId
            };
            // 场景广播
            channel.pushMessage(param);

            // 将场景里的其他玩家信息发给玩家
            // 从场景数据缓存中读取
            var memberlist = [];
            var sceneData = cachedb.syncHgetAll(sceneCacheKey);
            for (var index in sceneData) {
                var member = JSON.parse(sceneData[index]);
                memberlist.push({sid: member.sid, name: member.name});
            }
//            var users = channel.getMembers();       // 获取的是channel里uid列表
//            var memberlist = [];
//            for(var index in users) {
//                var member = JSON.parse(cachedb.syncGet(users[index]));
//                memberlist.push({sid: member.sid, name: member.name});
//                //memberlist.push(channel.getMember(users[index]));
//            }
            channelService.pushMessageByUids('onUserInfo', {members: memberlist}, [{
                uid: player.uid,
                sid: sessions[0].frontendId
            }]);

            // 将场景ID写入session
            sessions[0].set('scene', sceneId);
            sessions[0].push('scene', function(err) {
                if (err) {
                    console.error('set scene for session service failed! error is : ' + err.stack);
                }
            });

            // 将玩家添加进场景channel
            channel.add(player.uid, sessions[0].frontendId);

            // 将玩家添加进场景缓存表中
            cachedb.asyncHset(sceneCacheKey, 'player_' + player.uid, JSON.stringify(player));

            channelService.pushMessageByUids('onJoinScene', {code: 200, msg: '进入场景' + sceneId}, [{
                uid: player.uid,
                sid: sessions[0].frontendId
            }]);
            common.invokeCallback(cb);
        });
    });
};

// 离开场景
Handler.prototype.leave = function(uid, sid, cb) {
    var channel = this.channel;

    // 离开场景channel
    channel.leave(uid, sid);
    this.cachedb.asyncHdel(this.sceneCacheKey, 'player_' + uid);
    var param = {
        route: 'onLogout',
        uid: uid,
        sid: sid
    };
    channel.pushMessage(param);
    common.invokeCallback(cb);
};